<template>
    <div>

        <div class='container'>
            <div class='handle-box'>


                角色名称：
                <el-input v-model='query.rname' placeholder='角色名称' class='handle-input mr10'></el-input>

                创建时间：
                <el-date-picker
                    v-model='query.cdate'
                    align='right'
                    type='date'
                    placeholder='选择日期'
                    :picker-options='pickerOptions'
                    class='handle-input mr10'>
                </el-date-picker>


                <el-button type='primary' icon='el-icon-search' @click='handleSearch'>搜索</el-button>
                <el-button type='primary' icon='el-icon-refresh-left' @click='resetSearch'>重置</el-button>

            </div>
            <div style='margin-bottom: 20px'>
                <el-button type='primary' class='el-icon-circle-plus-outline' @click='handleAdd()'>添加</el-button>
                <el-button type='primary' class='el-icon-connection' @click='bindMenus()'>绑定菜单</el-button>
                <el-button type='danger' class='el-icon-delete' @click='handleBluckDelete()'>批量删除</el-button>
            </div>

            <el-table
                :data='tableData'
                border
                class='table'
                ref='multipleTable'
                header-cell-class-name='table-header'
                @selection-change='handleSelectionChange'
            >
                <el-table-column type='selection' width='55' align='center'></el-table-column>
                <el-table-column type='index' width='55' label='序号' align='center'></el-table-column>
                <!--隐藏角色id-->
                <el-table-column prop='rid' label='角色id' v-if='false'></el-table-column>
                <el-table-column prop='rname' label='角色名称'></el-table-column>
                <el-table-column prop='rdesc' label='角色描述'></el-table-column>
                <el-table-column prop='createTime' label='创建时间'></el-table-column>
                <el-table-column prop='updateTime' label='修改时间'></el-table-column>


                <!--工具栏-->
                <el-table-column label='操作' width='180' align='center'>
                    <template slot-scope='scope'>
                        <el-button
                            type='text'
                            icon='el-icon-edit'
                            class='yellow'
                            @click='handleEdit(scope.$index, scope.row)'
                        >编辑
                        </el-button>

                        <el-button
                            type='text'
                            icon='el-icon-delete'
                            class='red'
                            @click='handleDelete(scope.$index, scope.row)'
                        >删除
                        </el-button>
                    </template>
                </el-table-column>

            </el-table>
            <div class='pagination'>
                <el-pagination
                    background
                    layout='total, prev, pager, next'
                    :current-page='query.pageIndex'
                    :page-size='query.pageSize'
                    :total='pageTotal'
                    @current-change='handlePageChange'
                ></el-pagination>
            </div>
        </div>


        <!-- 添加弹出框 -->
        <el-dialog title='添加' :visible.sync='addVisible' width='30%'>
            <el-form ref='addValidateForm' :model='addform' :rules='rules' label-width='80px'>
                <el-form-item label='角色名称' prop='rname'>
                    <el-input v-model='addform.rname'></el-input>
                </el-form-item>
                <el-form-item label='角色描述' prop='rdesc'>
                    <el-input v-model='addform.rdesc'></el-input>
                </el-form-item>
            </el-form>
            <span slot='footer' class='dialog-footer'>
                        <el-button @click='cancel()'>取 消</el-button>
                        <el-button type='primary' @click="saveAdd('addValidateForm')">确 定</el-button>
                    </span>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title='编辑' :visible.sync='editVisible' width='30%'>
            <el-form ref='editValidateForm' :model='form' :rules='rules' label-width='80px'>
                <el-input v-if='false' v-model='form.rid'></el-input>
                <el-form-item label='角色名称' prop='rname'>
                    <el-input v-model='form.rname'></el-input>
                </el-form-item>
                <el-form-item label='角色描述' prop='rdesc'>
                    <el-input v-model='form.rdesc'></el-input>
                </el-form-item>
            </el-form>
            <span slot='footer' class='dialog-footer'>
                        <el-button @click='editCancel()'>取 消</el-button>
                        <el-button type='primary' @click="saveEdit('editValidateForm')">确 定</el-button>
                    </span>
        </el-dialog>


        <!-- 绑定菜单框 -->
        <el-dialog title='绑定菜单' :visible.sync='bindMenuVisible' width='30%'>

            <div class='zTreeDemoBackground left'>
                <ul id='treeDemo' class='ztree'></ul>
            </div>
            <span slot='footer' class='dialog-footer'>
                        <el-button @click='bindMenuVisible = false'>取 消</el-button>
                        <el-button type='primary' @click='saveBindMenu()'>确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
// import { fetchData } from '../../api/index';

export default {
    name: 'roletable',
    data() {
        return {
            //校验规则
            rules: {
                rname: [{ required: true, message: '请输入用户名', trigger: 'change' }],
                rdesc: [{ required: true, message: '请输入密码', trigger: 'change' },
                    { min: 0, max: 15, message: '长度在 0 到 15 个字符', trigger: 'blur' }]
            },
            query: {
                cdate: '',
                rname: '',
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [],
            multipleSelection: [],//多选值
            delList: [],//删除值
            editVisible: false,
            addVisible: false,
            bindMenuVisible: false,
            pageTotal: 0,
            form: {},//编辑表单
            addform: {},//添加表单
            idx: -1,
            id: -1,
            //ztree配置
            setting: {
                check: {
                    enable: true,
                    chkStyle: 'checkbox',
                    chkboxType: { 'Y': 'p', 'N': 's' }
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                }
            },
            funcTreeObj: {},
            zNodes: [],
            //快捷日期
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            }

        };
    },
    //初始化函数
    created() {
        this.global.saveFunLog(this.global.FUN_LOG_ENUM.ROLE_MAN);
        this.getData();
    },
    methods: {
        //初始化树
        getTree(rId) {
            console.log(rId);
            this.$http.post('/authserver/roleController/queryBindMenuByRid.json', rId).then(res => {
                console.log(res);
                if (res.data.status) {
                    this.zNodes = res.data.data;
                    this.funcTreeObj = $.fn.zTree.init($('#treeDemo'), this.setting, this.zNodes);
                }
            });
        },
        //保存权限菜单
        saveBindMenu() {
            const checkedObjs = this.funcTreeObj.getCheckedNodes(true);  //获取所有选中的节点
            console.log(checkedObjs);
            const arr = new Array();
            for (let i = 0; i < checkedObjs.length; i++) {
                const obj = checkedObjs[i]['id'];
                arr.push(obj);
            }
            arr.push(this.multipleSelection[0].rid);
            console.log(arr);
            this.$http.post('/authserver/roleController/bindMenus.json', arr).then(res => {
                if (res.data.status) {
                    this.$message.success('操作成功');
                } else {
                    this.$message.error(res.data.data.msg);
                }
                this.bindMenuVisible = false;
            });

        },
        // 给数据表格赋值
        getData() {
            this.$http.post('/authserver/roleController/selectPageRoles.json', this.query).then(res => {
                console.log(res);
                this.tableData = res.data.data.records;//数据
                this.pageTotal = res.data.data.total;//总数
            });
        },

        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);//重置为首页
            this.getData();//重新请求赋值
        },

        // 触发重置按钮
        resetSearch() {
            this.query.cdate = '';
            this.query.rname = '';
            this.$set(this.query, 'pageIndex', 1);//重置为首页
            this.getData();//重新请求赋值
        },
        //绑定菜单显示
        bindMenus() {
            console.log(this.multipleSelection);
            const len = this.multipleSelection.length;
            if (len != 1) {
                this.$message.error('请选择一个角色');
            } else {
                const rId = this.multipleSelection[0].rid;
                this.getTree(rId);
                this.bindMenuVisible = true;
            }
        },

        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    const rIds = new Array();
                    rIds.push(row.rid);
                    this.$http.post('/authserver/roleController/deleteRoleByIds.json', rIds).then(res => {
                        if (res.data.status) {
                            this.$message.success('删除成功');
                            this.tableData.splice(index, 1);
                        } else {
                            this.$message.error(res.data.msg);
                        }
                    });
                })
                .catch(() => {
                    this.$message.error(res.data.msg);
                });
        },
        //批量删除
        handleBluckDelete() {
            const length = this.multipleSelection.length;
            if (length < 1) {
                this.$message.error('请至少选择一个角色');
                return;
            }
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    const length = this.multipleSelection.length;
                    const rIds = new Array();
                    for (let i = 0; i < length; i++) {
                        rIds.push(this.multipleSelection[i].rid);
                    }
                    this.$http.post('/authserver/roleController/deleteRoleByIds.json', rIds).then(res => {
                        if (res.data.status) {
                            this.$message.success('删除成功');
                            this.getData();//重新请求赋值
                        } else {
                            this.$message.error(res.data.msg);
                        }
                    });
                })
                .catch(() => {
                    this.$message.error(res.data.msg);
                });
        },
        // 多选操作
        handleSelectionChange(val) {
            console.log(val);
            this.multipleSelection = val;
        },
        //
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 编辑操作 索引 列数据
        handleEdit(index, row) {
            this.idx = index;
            // this.form = row;
            this.form = Object.assign({}, this.form, row);
            this.editVisible = true;
        },
        //新增操作
        handleAdd() {
            this.addVisible = true;
        },
        //新增取消
        cancel() {
            this.addVisible = false;
            this.addform.rdesc = '';
            this.addform.rname = '';
        },
        // 保存新增
        saveAdd(addValidateForm) {
            this.$refs[addValidateForm].validate((valid) => {
                console.log(this.addform);
                if (valid) {
                    this.addVisible = false;//隐藏编辑框
                    console.log(this.addform);
                    this.$http.post('/authserver/roleController/addRole.json', this.addform).then(res => {
                        if (res.data.status) {
                            this.$message.success(res.data.msg);
                            this.getData();
                        }
                        this.addform.rdesc = '';
                        this.addform.rname = '';
                    });
                }

            });
        },
        //取消编辑
        editCancel() {
            this.editVisible = false;
        },
        // 保存编辑
        saveEdit(editValidateForm) {
            this.$refs[editValidateForm].validate((valid) => {
                console.log(valid);
                if (valid) {
                    this.editVisible = false;//隐藏编辑框
                    this.$http.post('/authserver/roleController/updateRoleById.json', this.form).then(res => {
                        if (res.data.status) {
                            this.$message.success(res.data.msg);
                            this.getData();
                        }
                    });
                }
            });
        },
        // 分页导航
        handlePageChange(val) {
            console.log(val);
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
@import '../../../plugings/zTreeStyle/zTreeStyle.css';

.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.yellow {
    color: #E6A23C;
}

.mr10 {
    margin-right: 10px;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
